<script setup lang="ts">
/*
 * @description: 会员选择组件
 * @author:
 * @date: 2025-8-9
 * @version: V1.0.0
 */
import { dataPageApi, dataBatchDelApi } from '@/api/member'
import type { ItemFormInt } from '@/api/member/types'
import { usePage } from '@/hooks/system/useFramework'
import AddEditForm from './AddEditForm.vue'

// 定义组件属性
interface Props {
  modelValue: ItemFormInt | null
  placeholder?: string
}

// 定义事件
interface Emits {
  (e: 'update:modelValue', value: ItemFormInt | null): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: null,
  placeholder: '请选择会员'
})

const emit = defineEmits<Emits>()

// 引用
const tableRef = ref()
const queryFormRef = ref()
const selectMemberRef = ref()

// 数据状态
const dialogVisible = ref(false)
const selectedMember = ref<ItemFormInt | null>(null)

// 查询参数
const queryParams = ref({
  keywords: ''
})

// 使用项目现有的usePage hook处理分页逻辑
const { queryPage, tableData, loading, handleQuery, handleResetQuery } = usePage<ItemFormInt>(
  dataPageApi,
  dataBatchDelApi,
  queryParams,
  queryFormRef,
  selectMemberRef
)

// 计算属性：显示在输入框中的会员信息
const displayText = computed(() => {
  if (props.modelValue && props.modelValue.username) {
    return `${props.modelValue.username} (${props.modelValue.phone})`
  }
  return ''
})

// 打开选择对话框
const openDialog = () => {
  dialogVisible.value = true
  selectedMember.value = props.modelValue
  nextTick(() => {
    // 初始化数据
    handleQuery()
  })
}

// 选择会员
const handleSelectMember = (row: ItemFormInt) => {
  selectedMember.value = row
}

// 确认选择
const handleConfirm = () => {
  if (selectedMember.value) {
    emit('update:modelValue', selectedMember.value)
  }
  dialogVisible.value = false
}

const handleClear = () => {
  emit('update:modelValue', null)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  selectedMember.value = null
}

// 表格行点击事件
const handleRowClick = (row: ItemFormInt) => {
  tableRef.value?.setCurrentRow(row)
  handleSelectMember(row)
}

defineExpose({
  openDialog
})

const addEditFormRef = ref()
const handleAdd = () => {
  addEditFormRef.value.open('add')
}
</script>

<template>
  <div class="select-member">
    <el-input v-model="displayText" :placeholder="placeholder" readonly @click="openDialog">
      <template #suffix>
        <el-icon v-if="displayText" style="cursor: pointer" @click="handleClear"><CircleClose /></el-icon>
        <el-icon v-else><ArrowDown /></el-icon>
      </template>
    </el-input>

    <!-- 会员选择对话框 -->
    <el-dialog v-model="dialogVisible" title="选择会员" width="800px" @close="handleClose" top="5vh">
      <div class="select-member__dialog">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-card shadow="never">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
              <el-form-item label="关键字" prop="keywords">
                <el-input v-model="queryParams.keywords" placeholder="姓名/电话" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
                <el-button type="success" icon="plus" @click="handleAdd">新增</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>

        <!-- 会员列表 -->
        <el-card shadow="never" class="data-table">
          <el-table ref="tableRef" v-loading="loading" fit height="400" highlight-current-row :data="tableData" border @row-click="handleRowClick">
            <el-table-column type="index" width="55" label="#" align="center" />
            <el-table-column label="姓名" prop="username" />
            <el-table-column label="电话" prop="phone">
              <template #default="scope">
                {{ scope.row.phone || '暂无' }}
              </template>
            </el-table-column>
            <el-table-column label="性别" prop="sex">
              <template #default="scope">
                <dict-label code="sex" :model-value="scope.row.sex" />
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-if="queryPage.total > 0"
            layout="prev, pager, next, sizes, total"
            :total="queryPage.total"
            v-model:current-page="queryPage.pageNum"
            v-model:page-size="queryPage.pageSize"
            @current-change="handleQuery"
            @size-change="handleQuery"
          />
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" :disabled="!selectedMember" @click="handleConfirm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增、编辑弹窗 -->
    <AddEditForm ref="addEditFormRef"></AddEditForm>
  </div>
</template>

<style lang="scss" scoped>
.select-member {
  width: 100%;

  &__dialog {
    .search-container {
      margin-bottom: 16px;

      :deep(.el-card__body) {
        padding: 16px;
      }
    }

    .data-table {
      :deep(.el-card__body) {
        padding: 0;
      }

      .el-table {
        margin-bottom: 16px;
      }
    }
  }

  .dialog-footer {
    text-align: right;
  }
}
</style>
